import {calendarSignRebate, isCalendarSignRebate, queryUserActivityAccount, queryUserCreditAccount} from "@/apis";
import React, {useEffect, useState} from "react";
import {UserActivityAccountVO} from "@/types/UserActivityAccountVO";

// @ts-ignore
export function MemberCard({allRefresh}) {
    const [refresh, setRefresh] = useState(0);

    const [dayCount, setDayCount] = useState(0)
    const [creditAmount, setCreditAmount] = useState(0)
    const [sign, setSign] = useState(false);

    const [userId, setUserId] = useState('');

    const getParams = async () => {
        setUserId(String(new URLSearchParams(window.location.search).get('userId')));
    }

    const handleRefresh = () => {
        setRefresh(refresh + 1)
    };

    // 获取当前日期
    const currentDate = new Date();
    // 格式化日期为 YYYY年MM月DD日
    const formattedDate = currentDate.getFullYear() + '年'
        + ('0' + (currentDate.getMonth() + 1)).slice(-2) + '月'
        + ('0' + currentDate.getDate()).slice(-2) + '日';

    const queryUserActivityAccountHandle = async () => {
        const queryParams = new URLSearchParams(window.location.search);
        const result = await queryUserActivityAccount(String(queryParams.get('userId')), Number(queryParams.get('activityId')));
        // 查询账户数据
        const {code, info, data}: { code: string; info: string; data: UserActivityAccountVO } = await result.json();

        if (code != "0000") {
            window.alert("查询活动账户额度，接口调用失败 code:" + code + " info:" + info)
            return;
        }

        // 日可抽奖额度
        setDayCount(data.dayCountSurplus)
    }

    const queryUserCreditAccountHandle = async () => {
        const queryParams = new URLSearchParams(window.location.search);
        const result = await queryUserCreditAccount(String(queryParams.get('userId')));
        const {code, info, data}: { code: string; info: string; data: number } = await result.json();

        if (code != "0000") {
            window.alert("查询活动账户额度，接口调用失败 code:" + code + " info:" + info)
            return;
        }

        // 用户积分
        setCreditAmount(data)
    }

    const calendarSignRebateHandle = async () => {
        if (sign) {
            window.alert("今日已签到！")
            return;
        }
        const queryParams = new URLSearchParams(window.location.search);
        const result = await calendarSignRebate(String(queryParams.get('userId')));
        const {code, info}: { code: string; info: string; } = await result.json();

        if (code != "0000" && code != "0003") {
            window.alert("日历签到返利接口，接口调用失败 code:" + code + " info:" + info)
            return;
        }

        setSign(true);

        // 设置一个3秒后执行的定时器
        const timer = setTimeout(() => {
            handleRefresh()
        }, 550);

        // 清除定时器，以防组件在执行前被卸载
        return () => clearTimeout(timer);
    }

    const isCalendarSignRebateHandle = async () => {

        const queryParams = new URLSearchParams(window.location.search);
        const result = await isCalendarSignRebate(String(queryParams.get('userId')));
        const {code, info, data}: { code: string; info: string; data: boolean } = await result.json();

        if (code != "0000") {
            window.alert("判断是否签到接口，接口调用失败 code:" + code + " info:" + info)
            return;
        }

        setSign(data);
    }


    useEffect(() => {
        getParams().then(r => {
        });

        queryUserActivityAccountHandle().then(r => {
        });

        queryUserCreditAccountHandle().then(r => {
        });

        isCalendarSignRebateHandle().then(r => {
        });
    }, [refresh, allRefresh])

    return (
        <>

            <div
                className="relative max-w-2xl mx-auto bg-gradient-to-br from-blue-800 to-teal-700 rounded-xl shadow-xl overflow-hidden mb-8 transition-all">
                {/* 用户ID区域 */}
                <div className="px-6 pt-3 pb-1">
                    <div
                        className="text-sm bg-white/10 text-blue-100 px-3 py-1 rounded-full backdrop-blur-sm inline-flex items-center">
                        <span className="mr-2 text-base">👤</span>
                        ID: <span className="font-mono ml-1">{userId}</span>
                    </div>
                </div>

                <div className="flex flex-row">
                    {/* 左侧内容区域 */}
                    <div className="p-6 flex-1 min-w-[300px]">
                        {/* 标题 */}
                        <div className="mb-4">
                            <h2 className="text-2xl font-bold text-white inline-block">
                                营销会员卡
                                <span className="ml-2 text-teal-300 text-lg align-middle">VIP</span>
                            </h2>
                        </div>

                        {/* 数据展示 */}
                        <div className="space-y-6">
                            <div className="flex items-center text-blue-50">
                    <span className="mr-4 p-3 bg-white/10 rounded-lg text-xl">
                        💰
                    </span>
                                <div className="flex-1">
                                    <p className="text-base text-blue-100/90 mb-1">可用积分</p>
                                    <p className="text-2xl font-semibold tracking-wide">
                                        {creditAmount || 0}<span className="text-sm ml-1">⭐</span>
                                    </p>
                                </div>
                            </div>

                            <div className="flex items-center text-blue-50">
                    <span className="mr-4 p-3 bg-white/10 rounded-lg text-xl">
                        🪅
                    </span>
                                <div className="flex-1">
                                    <p className="text-base text-blue-100/90 mb-1">可用抽奖次数</p>
                                    <p className="text-2xl font-semibold tracking-wide">
                                        {dayCount || 0}<span className="text-sm ml-1">🎲</span>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* 右侧操作区域 */}
                    <div className="w-[280px] border-l border-white/10 flex flex-col justify-between p-4">
                        {/* 日期显示 */}
                        <div className="text-blue-100/90 text-base font-medium text-center mb-3">
                            📅 {formattedDate}
                        </div>

                        {/* 签到按钮 */}
                        <div className="flex-1 flex flex-col items-center justify-center">
                            <button
                                onClick={calendarSignRebateHandle}
                                className={`w-32 h-32 rounded-full shadow-lg transition-transform ${
                                    sign
                                        ? "bg-emerald-400 cursor-default"
                                        : "bg-amber-400 hover:bg-amber-500 animate-pulse"
                                } ${!sign && "hover:scale-105"} flex items-center justify-center`}
                            >
                    <span className="text-white font-bold text-2xl">
                        {sign ? "已签" : "签到"}
                    </span>
                            </button>
                        </div>

                        {/* 刷新按钮 */}
                        <div className="text-center pt-3">
                            <button
                                onClick={handleRefresh}
                                className="bg-white/90 hover:bg-white text-blue-700 font-semibold py-2 px-5 rounded-full
                    shadow-md transition-all hover:scale-105 text-base flex items-center mx-auto"
                            >
                                <svg xmlns="http://www.w3.org/2000/svg"
                                     className="h-5 w-5 mr-1.5"
                                     fill="none"
                                     viewBox="0 0 24 24"
                                     stroke="currentColor">
                                    <path strokeLinecap="round"
                                          strokeLinejoin="round"
                                          strokeWidth={2}
                                          d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                                </svg>
                                刷新
                            </button>
                        </div>
                    </div>
                </div>
            </div>

        </>
    )

}
